package com.situ.mall.controller.front;

import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.print.attribute.standard.OrientationRequested;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.mall.VO.CartItemVO;
import com.situ.mall.VO.CartVO;
import com.situ.mall.common.ServerResponse;
import com.situ.mall.entity.Cart;
import com.situ.mall.entity.Order;
import com.situ.mall.entity.OrderItem;
import com.situ.mall.entity.Product;
import com.situ.mall.entity.User;
import com.situ.mall.mapper.OrderItemMapper;
import com.situ.mall.service.ICartService;
import com.situ.mall.service.IOrderItemService;
import com.situ.mall.service.IProductService;
import com.situ.mall.service.impl.CartServiceImpl;

@Controller
@RequestMapping("/cart")
public class FrontCartController {
	private static final Integer CART_CHCKED = null;
	// 设置到cookie中购物车名字
	private final String CART_COOKIE = "cart_cookie";
	// 购物车选中状态
	private final Integer CART_CHECKED = 1;
	// 购物车未选中状态
	private final Integer CART_UNCHECKED = 0;

	@Autowired
	private IProductService ProductService;
	@Autowired
	private ICartService CartService;
	@Autowired
	private IOrderItemService orderItemService;

	// 关于购物车的controller
	// 先跳转到购物车展示界面
	@RequestMapping("/getCartPage.shtml")
	public String getCartPage(HttpServletRequest request, Model model) {
		// 将cookie中购物车转换成cartVO对象
		CartVO cartVO = getCartVOFromCookie(request);
		List<CartItemVO> cartItemVOList = cartVO.getCartItemVOList();
		// 要通过这个cartItemVO中的 product 的ID 查出product全部信息。然后把原来的product全部替换掉？
		for (CartItemVO cartItemVO : cartItemVOList) {
			Product product = ProductService.selectByPrimaryKey(cartItemVO.getProduct().getId().intValue());
			cartItemVO.setProduct(product);
		}
		model.addAttribute("cartVO", cartVO);

		// 跳转到购物车网扯
		return "/cart/cart";
	}

	// addOrUpdate
	@RequestMapping("/addOrUpdate.shtml")
	@ResponseBody
	public ServerResponse addOrUpdate(Integer productId, Integer amount, Integer isChecked, HttpServletRequest request,
			HttpServletResponse response) {
		// 1.将cookie里面的购物车转换成cartVO对象
		CartVO cartVO = getCartVOFromCookie(request);
		if (null == cartVO) {
			cartVO = new CartVO();
		}
		// 2.向cartVO中添加购物项
		boolean result = addOrUpdate(cartVO, productId, amount, isChecked);
		if (result == false) {
			return ServerResponse.createError("添加购物车失败");
		}
		// 将cartVO对象设置到cookie
		setCartVOToCookie(cartVO, response);
		return ServerResponse.createSuccess("添加购物车成功");
	}

	// addOrUpdateCart
	@RequestMapping("/addOrUpdateCart")
	@ResponseBody
	public ServerResponse addOrUpdateCart(HttpServletResponse response, Integer isChecked, Integer amount,
			HttpServletRequest request, Integer productId) {
		//判断是否为登录状态
		
		// 1.先cookie转换成cartVO
		CartVO cartVO = getCartVOFromCookie(request);
		// 如果是空的 就先new一个
		if (null == cartVO) {
			cartVO = new CartVO();
		}
		// 往cartVO中添加购物项(购物车内容转换成cartVO对象)
		boolean isExist = false;
		List<CartItemVO> cartItemVOList = cartVO.getCartItemVOList();
		Product product = ProductService.selectByPrimaryKey(productId);
		for (CartItemVO cartItemVO : cartItemVOList) {
			// 如果productId对应的商品在cartVO中，只更新数量
			if (cartItemVO.getProduct().getId().intValue() == productId.intValue()) {
				isExist = true;
				// 只更新isChecked 不传递amount amount 还是NULL
				if (null != amount) {
					int newAmount = cartItemVO.getAmount() + amount;
					// 判断商品有没有超过库存
					if (newAmount > product.getStock()) {
						// 超出，返回 添加失败
						return ServerResponse.createSuccess("超出库存");
					}
					cartItemVO.setAmount(newAmount);
				}
				// 如果是未选中状态，更新成选中状态
				if (null != isChecked) {
					cartItemVO.setIsChecked(isChecked);
				}
				setCartVOToCookie(cartVO, response);
				return ServerResponse.createSuccess("更新成功");
			}
		}
		// productId对应的商品不在cartVO里面，添加到cartVO
		if (isExist == false) {
			CartItemVO cartItemVO = new CartItemVO();
			Product prod = new Product();
			prod.setId(productId);
			cartItemVO.setProduct(prod);
			cartItemVO.setAmount(amount);
			cartItemVO.setIsChecked(CART_CHECKED);

			cartItemVOList.add(cartItemVO);
		}

		// 将cartVO对象设置到cookie中
		setCartVOToCookie(cartVO, response);
		return ServerResponse.createSuccess("添加购物车成功");
	}

	// 将购物车中商品删除
	@RequestMapping("/deleteById.shtml")
	@ResponseBody
	public ServerResponse deleteById(Integer productId, HttpServletRequest request, HttpServletResponse response) {
		// 1.将cookie中的购物车转化为cartVO
		CartVO cartVO = getCartVOFromCookie(request);
		if (null == cartVO) {
			return ServerResponse.createSuccess("获取购物车失败");
		}

		List<CartItemVO> cartItemVOList = cartVO.getCartItemVOList();
		// 以下是什么?
		Iterator<CartItemVO> iterator = cartItemVOList.iterator();
		while (iterator.hasNext()) {
			CartItemVO cartItemVO = iterator.next();
			if (cartItemVO.getProduct().getId().intValue() == productId.intValue()) {
				iterator.remove();
			}
		}
		// 将cartvo对象写入cookie中
		setCartVOToCookie(cartVO, response);

		return ServerResponse.createSuccess("删除商品成功");
	}

	// 先只是跑出来订单界面
	@RequestMapping("/getplace2")
	public String getplace2(HttpServletRequest request, Model model) {
		// 将cookie中数据转换成cartVO对象
		CartVO cartVO = getCartVOFromCookie(request);
		List<CartItemVO> cartItemVOList = cartVO.getCartItemVOList();
		// 根据cartItemVO 的 product 的ID 查出全部信息，然后把原来的product全部替换掉
		for (CartItemVO cartItemVO : cartItemVOList) {
			Product product = ProductService.selectByPrimaryKey(cartItemVO.getProduct().getId());
			cartItemVO.setProduct(product);
		}
		model.addAttribute("cartVO", cartVO);
		return "/place/place_order";
	}

	// 跳转到订单页，还要在把cart表中关于用户的查出来。
	@RequestMapping("/getplace.shtml")
	public String getplace(HttpSession session, Model model) {
		// 在session中获得user对象
		User user = (User) session.getAttribute("USER");
		// 根据userID查询cart表中的product
		Integer userId = user.getId();
		List<Cart> cart = CartService.select(userId);
		model.addAttribute("cart", cart);
		// 还要根据productID 在orderItem中 查询 商品信息
		for (Cart cart2 : cart) {
			Integer productId = cart2.getProductId();
			Integer primarykey = cart2.getProductId();
			OrderItem orderItem = orderItemService.selectByProductId(productId);
			Product product = ProductService.selectByPrimaryKey(primarykey);
			model.addAttribute("orderItem", orderItem);
			model.addAttribute("product", product);
		}
		
		return "/place/place_order1";
	}

	/***
	 * 将cartVO对象设置到cookie中
	 * 
	 * @param cartVO
	 * @param response
	 */
	private void setCartVOToCookie(CartVO cartVO, HttpServletResponse response) {
		ObjectMapper objectMapper = new ObjectMapper();
		// 对象不为null才转换
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		// 将cartVO对象以json形式放到cookie中
		StringWriter stringWriter = new StringWriter();
		try {
			objectMapper.writeValue(stringWriter, cartVO);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 将购物车json放到cookie中
		Cookie cookie = new Cookie(CART_COOKIE, stringWriter.toString());
		// 设置cookie储存时间
		cookie.setMaxAge(60 * 60 * 24);// 储存时间为一天
		// 设置cookie路径
		// ?
		cookie.setPath("/");
		// 将cookie发送到浏览器中
		response.addCookie(cookie);
	}

	/***
	 * 
	 * @param cartVO
	 * @param productId
	 * @param amount
	 * @param isChecked
	 * @return
	 */
	private boolean addOrUpdate(CartVO cartVO, Integer productId, Integer amount, Integer isChecked) {
		boolean isExist = false;
		List<CartItemVO> cartItemVOList = cartVO.getCartItemVOList();
		Product product = ProductService.selectByPrimaryKey(productId);
		for (CartItemVO cartItemVO : cartItemVOList) {
			// 1.productID对应的商品在cartVO中的话，只是将数量更新
			if (cartItemVO.getProduct().getId().intValue() == productId.intValue()) {
				isExist = true;
				// 只是更新isChecked，没有传递amount，所以amount是null
				if (null != amount) {
					int newAmount = cartItemVO.getAmount() + amount;
					// 判断商品有没有超过库存
					if (newAmount > product.getStock()) {
						// 超出，返回false
						return false;
					}
					cartItemVO.setAmount(newAmount);
				}
				if (null != isChecked) {
					// 将选中状态修改为 选中状态 (isChecked = 1)
					cartItemVO.setIsChecked(isChecked);
				}
			}
		}
		// 2.productId 对应的商品没在cartVO中，把它添加到cartItemVO中
		if (isExist == false) {
			CartItemVO cartItemVO = new CartItemVO();
			Product prod = new Product();
			prod.setId(productId);
			cartItemVO.setAmount(amount);
			cartItemVO.setIsChecked(CART_CHECKED);// ?
			cartItemVO.setProduct(prod);

			cartItemVOList.add(cartItemVO);

		}
		return true;
	}

	/**
	 * 将cookie中的购物车信息转化为cartVO 对象
	 */
	private CartVO getCartVOFromCookie(HttpServletRequest request) {
		CartVO cartVO = null;
		ObjectMapper objectMapper = new ObjectMapper();
		// 只有对象不为null进行转换
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		// 将客户端中cookie拿出来?
		Cookie[] cookies = request.getCookies();
		if (null != cookies && cookies.length != 0) {
			for (Cookie cookie : cookies) {
				if (CART_COOKIE.equals(cookie.getName())) {
					// 找到了购物车中cookie的购物信息
					String value = cookie.getValue();
					// 将json字符串转换成java对象
					try {
						cartVO = objectMapper.readValue(value, CartVO.class);
					} catch (JsonParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JsonMappingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		}

		return cartVO;
	}

}
